package com.cjl.dental_clinic.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjl.dental_clinic.Req.MedicineReq;
import com.cjl.dental_clinic.Req.OrderReq;
import com.cjl.dental_clinic.entity.Order;
import com.cjl.dental_clinic.entity.Prescription;
import com.cjl.dental_clinic.mapper.OrderMapper;
import com.cjl.dental_clinic.service.MedicineService;
import com.cjl.dental_clinic.service.OrderService;
import com.cjl.dental_clinic.service.PrescriptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

/**
 * @description:
 * @author: cjl
 * @time: 2024/04/13 21:14
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private MedicineService medicineService;
    @Autowired
    private PrescriptionService prescriptionService;
    @Override
    public List<OrderReq> listOrder(String name) {
        BigDecimal account = new BigDecimal(0);
        List<OrderReq> orderReqs = baseMapper.listOrder(name);
        for (OrderReq orderReq : orderReqs) {
            account = new BigDecimal(0);
            Prescription one = prescriptionService.getOne(new QueryWrapper<Prescription>().select("id").eq("patient_id", orderReq.getPatientId()));
            List<MedicineReq> reqs = medicineService.listMedicine(one.getId());
            for (MedicineReq req : reqs) {
                account = NumberUtil.add(account,req.getUnitPrice());
            }
            orderReq.setMedicineList(reqs);
            orderReq.setAmount(account);
        }
        return orderReqs;
    }

    @Override
    public Boolean pay(Integer id) {
        if (generateRandomOneOrTwo()==1){
            baseMapper.update(new UpdateWrapper<Order>().set("pay_status", 1).eq("id", id));
            return true;
        }
        baseMapper.update(new UpdateWrapper<Order>().set("pay_status", 2).eq("id", id));
        return false;
    }

    public static int generateRandomOneOrTwo() {
        Random random = new Random();
        // 生成一个0（包含）到2（不包含）之间的随机整数
        int randomInt = random.nextInt(2);
        // 将生成的0或1映射为1或2
        return randomInt + 1;
    }
}
